//
//  ViewController.m
//  changeEXIF
//
//  Created by iptv-macmini on 2020/7/3.
//  Copyright © 2020 iptv-macmini. All rights reserved.
//

#import "ViewController.h"
#import "TZImagePickerController.h"
#import <MapKit/MapKit.h>

#define SCREEN_WIDTH        (AppContext.deviceInfo.screenWidth)
#define SCREEN_HEIGHT       (AppContext.deviceInfo.screenHeight)

#define LAT_OFFSET_0(x,y) -100.000 + 2.000 * x + 3.000 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x))
#define LAT_OFFSET_1 (20.000 * sin(6.000 * x * M_PI) + 20.000 * sin(2.000 * x * M_PI)) * 2.000 / 3.000
#define LAT_OFFSET_2 (20.000 * sin(y * M_PI) + 40.000 * sin(y / 3.000 * M_PI)) * 2.000 / 3.000
#define LAT_OFFSET_3 (160.000 * sin(y / 12.000 * M_PI) + 320 * sin(y * M_PI / 30.000)) * 2.000 / 3.000
#define LON_OFFSET_0(x,y) 300.000 + x + 2.000 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x))
#define LON_OFFSET_1 (20.000 * sin(6.000 * x * M_PI) + 20.000 * sin(2.000 * x * M_PI)) * 2.000 / 3.000
#define LON_OFFSET_2 (20.000 * sin(x * M_PI) + 40.000 * sin(x / 3.000 * M_PI)) * 2.000 / 3.000
#define LON_OFFSET_3 (150.000 * sin(x / 12.000 * M_PI) + 300.000 * sin(x / 30.000 * M_PI)) * 2.000 / 3.000

#define RANGE_LON_MAX 137.8347
#define RANGE_LON_MIN 72.004
#define RANGE_LAT_MAX 55.8271
#define RANGE_LAT_MIN 0.8293

#define jzA 6378245.000
#define jzEE 0.00669342162296594323

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *choiceImgBtn;
@property (weak, nonatomic) IBOutlet UIButton *OKBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segControl;

@property (nonatomic, strong) NSArray *photoArr;
@property (nonatomic, strong) NSArray *assetsArr;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKPointAnnotation *annotation;
@property (nonatomic, strong) CLLocation *location;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.photoArr = [[NSArray alloc] init];
    self.assetsArr = [[NSArray alloc] init];
    
    self.layout.estimatedItemSize = CGSizeMake((CGRectGetWidth(self.view.bounds) - 35.00f)/4.0f, (CGRectGetWidth(self.view.bounds) - 35.00f)/4.0f);
    self.collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    
    // 是否可以缩放
    self.mapView.zoomEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTipView:)];
    [self.mapView addGestureRecognizer:tapGesture];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
        BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

-(CLLocationManager *)locationManager
{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        // 设置定位距离过滤参数 （当上次定位和本次定位之间的距离 > 此值时，才会调用代理通知开发者）
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        // 设置定位精度 （精确度越高，越耗电，所以需要我们根据实际情况，设定对应的精度）
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        _locationManager.delegate = self;
    }
    return _locationManager;
}

- (IBAction)choicePhotoAct:(id)sender {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:100 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按钮
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.scaleAspectFillCrop = YES;
    
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = NO;
    
    __weak typeof(self) weakSelf = self;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.photoArr = photos;
        strongSelf.assetsArr = assets;
        [strongSelf.collectionView reloadData];
    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (IBAction)configAct:(id)sender {
    if (self.assetsArr.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"请添加照片" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:alertAction];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    if (!self.location) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"请确认定位信息" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:alertAction];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    if (self.segControl.selectedSegmentIndex == 2) {
        PHAsset *asset = self.assetsArr[0];
        if (asset.location) {
            self.location = asset.location;
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"该照片没有定位信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
            [alert addAction:alertAction];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
    }
    
    //设置全局dispatch_group_t group;
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"修改成功，请打开相册查看" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:alertAction];
        [self presentViewController:alert animated:YES completion:nil];
    });
    
    for (PHAsset *asset in self.assetsArr) {
        dispatch_group_enter(group);
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest * changeRequest = [PHAssetChangeRequest changeRequestForAsset:asset];
            changeRequest.location = self.location;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            dispatch_group_leave(group);
            if (success) {
                NSLog(@"修改成功");
            } else {
                NSLog(@"修改失败");
            }
        }];
    }
}

- (IBAction)segControlChanged:(UISegmentedControl*)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
        {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized ||
                [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
                [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways )
            {
                [self.locationManager startUpdatingLocation];
            }else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
                if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                    //获取授权认证
                    [self.locationManager requestAlwaysAuthorization];
                }
            }else{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:[NSDictionary dictionary] completionHandler:^(BOOL success) {
                }];
            }
        }
            break;
        case 1:
        {
            [self.locationManager stopUpdatingLocation];
        }
            break;
        case 2:
        {
            if (self.annotation) {
                [self.locationManager stopUpdatingLocation];
            }
            [self.mapView removeAnnotation:self.annotation];
            self.annotation = nil;
        }
            break;
        default:
            break;
    }
}

- (void)tapTipView:(UITapGestureRecognizer *)tapGes
{
    if (self.segControl.selectedSegmentIndex == 1) {
        //点击的坐标
        CGPoint touchPoint = [tapGes locationInView:self.mapView];
        // 将坐标转换为经纬度
        CLLocationCoordinate2D center = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
        
        self.location = [[CLLocation alloc] initWithLatitude:center.latitude longitude:center.longitude];
        [self addAnnotation];
    }
}

- (void)addAnnotation{
    if (self.annotation) {
        [self.mapView removeAnnotation:self.annotation];
    }
    self.annotation = [[MKPointAnnotation alloc] init];
    [self.annotation setCoordinate:CLLocationCoordinate2DMake(self.location.coordinate.latitude, self.location.coordinate.longitude)];
    [self.mapView addAnnotation:self.annotation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) {
        // 包含区，街道等信息的地标对象
        CLPlacemark *placemark = [placemarks firstObject];
        self.annotation.title = placemark.name;
        self.annotation.subtitle = [NSString stringWithFormat:@"%@-%@-%@",placemark.locality,placemark.subLocality,placemark.thoroughfare];
    }];
}

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    }else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark - collection delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    UIImageView *imgView = [cell.contentView viewWithTag:100];
    if (!imgView) {
        imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        imgView.tag = 100;
        imgView.contentMode =  UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        [cell.contentView addSubview:imgView];
    }
    imgView.image = [self.photoArr objectAtIndex:indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{}

#pragma mark - locationManager

//定位到的代理方法
-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations
{
    self.location = locations.lastObject;
    [self addAnnotation];
}

/**
 *  当用户授权状态发生变化时调用
 */
-(void)locationManager:(nonnull CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            self.segControl.selectedSegmentIndex = 0;
            [self.locationManager startUpdatingLocation];
            break;
        }
        default:
            break;
    }
}

-(double)transformLat:(double)x bdLon:(double)y
{
    double ret = LAT_OFFSET_0(x, y);
    ret += LAT_OFFSET_1;
    ret += LAT_OFFSET_2;
    ret += LAT_OFFSET_3;
    return ret;
}

-(double)transformLon:(double)x bdLon:(double)y
{
    double ret = LON_OFFSET_0(x, y);
    ret += LON_OFFSET_1;
    ret += LON_OFFSET_2;
    ret += LON_OFFSET_3;
    return ret;
}

-(BOOL)outOfChina:(double)lat bdLon:(double)lon
{
    if (lon < RANGE_LON_MIN || lon > RANGE_LON_MAX)
        return true;
    if (lat < RANGE_LAT_MIN || lat > RANGE_LAT_MAX)
        return true;
    return false;
}


-(CLLocationCoordinate2D)gcj02Encrypt:(double)ggLat bdLon:(double)ggLon
{
    CLLocationCoordinate2D resPoint;
    double mgLat;
    double mgLon;
    if ([self outOfChina:ggLat bdLon:ggLon]) {
        resPoint.latitude = ggLat;
        resPoint.longitude = ggLon;
        return resPoint;
    }
    double dLat = [self transformLat:(ggLon - 105.0)bdLon:(ggLat - 35.0)];
    double dLon = [self transformLon:(ggLon - 105.0) bdLon:(ggLat - 35.0)];
    double radLat = ggLat / 180.0 * M_PI;
    double magic = sin(radLat);
    magic = 1 - jzEE * magic * magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((jzA * (1 - jzEE)) / (magic * sqrtMagic) * M_PI);
    dLon = (dLon * 180.0) / (jzA / sqrtMagic * cos(radLat) * M_PI);
    mgLat = ggLat + dLat;
    mgLon = ggLon + dLon;
    
    resPoint.latitude = mgLat;
    resPoint.longitude = mgLon;
    return resPoint;
}

-(CLLocationCoordinate2D)wgs84ToGcj02:(CLLocationCoordinate2D)location
{
    return [self gcj02Encrypt:location.latitude bdLon:location.longitude];
}

@end
